﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.Diagnostics;
using BYRBBS.Model;
using BYRBBS.Util;

namespace BYRForum
{
    public partial class ThreadsDetailPage : PhoneApplicationPage
    {

        public int total_page = 1;
        public int current_page = 1;
        bool TapHandled = false;
        //bool if_loaded = false;
        ApplicationBarIconButton BarButtonFirstPage;
        ApplicationBarIconButton BarButtonPreviousPage;
        ApplicationBarIconButton BarButtonNextPage;
        ApplicationBarIconButton BarButtonLastPage;

        public ThreadsDetailPage()
        {
            InitializeComponent();
            this.SetValue(SystemTray.IsVisibleProperty, !(bool)this.GetValue(SystemTray.IsVisibleProperty));
            BarButtonFirstPage = this.ApplicationBar.Buttons[0] as ApplicationBarIconButton;
            BarButtonPreviousPage = this.ApplicationBar.Buttons[1] as ApplicationBarIconButton;
            BarButtonNextPage = this.ApplicationBar.Buttons[2] as ApplicationBarIconButton;
            BarButtonLastPage = this.ApplicationBar.Buttons[3] as ApplicationBarIconButton;
            DisableApplicationBar();
            
        }

        //private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e)
        //{

        //        App.ArticleList.Items.Clear();
        //        string url = ByrApi.apiUrl + "/threads/" + App.TempThreadItem.BoardName + "/" +
        //                     App.TempThreadItem.GroupID + ByrApi.Encode + ByrApi.appkey+"page="+current_page;
        //        HttpUtil.HttpGet(url, HttpWebRequset_Callback);
        //        progressBarWait.Visibility = Visibility.Visible;
        //        ThreadDetailListBox.ItemsSource = App.ArticleList.Items;

            
        //}


        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {
            if (App.ThreadDetailSourcePage == "UserInfoPage")
            {
                App.ThreadDetailSourcePage = "";
                base.OnNavigatedTo(e);
                return;
            }
            App.ArticleList.Items.Clear();
            string url = ByrApi.apiUrl + "/threads/" + App.TempThreadItem.BoardName + "/" +
                         App.TempThreadItem.GroupID + ByrApi.Encode + ByrApi.appkey + "page=" + current_page;
            HttpUtil.HttpGet(url, HttpWebRequset_Callback);
            progressBarWait.Visibility = Visibility.Visible;
            ThreadDetailListBox.ItemsSource = App.ArticleList.Items;
            base.OnNavigatedTo(e);
        }


        public void GoToPage(int pageNum)
        {
            
            string url = ByrApi.apiUrl + "/threads/" + App.TempThreadItem.BoardName + "/" +
                         App.TempThreadItem.GroupID + ByrApi.Encode + ByrApi.appkey + "page=" + (pageNum).ToString();
            HttpUtil.HttpGet(url, HttpWebRequset_Callback);
            progressBarWait.Visibility = Visibility.Visible;
        }

        private void HttpWebRequset_Callback(IAsyncResult asynchronousResult)
        {
            try
            {
                //网络有错误将会在这里抛出异常
                string result = HttpUtil.ReadToEnd(asynchronousResult);
                Debug.WriteLine(result);
                string ErrorInfo;
                Threads threads = ParseUtil.ParseXml<Threads>(result, out ErrorInfo);

                current_page = Convert.ToInt32(threads.Pag.Page_current_count);
                total_page = Convert.ToInt32(threads.Pag.Page_all_count);

                if (threads == null)
                {
                    this.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        MessageBox.Show(ErrorInfo);
                        progressBarWait.Visibility = Visibility.Collapsed;
                        NavigationService.Navigate(new Uri("/BYRForum;component/ThreadsListPage.xaml?BoardName=" + App.TempBoardItem.Description, UriKind.Relative));
                    }));
                }
                else
                {
                    this.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        App.ArticleList.Items.Clear();

                        App.ArticleList.LoadData(threads.ArticleItems);
                        progressBarWait.Visibility = Visibility.Collapsed;
                        ShowApplicationBarState(current_page,total_page);
                    }));
                }
            }
            catch(Exception e)
            {
                Debug.WriteLine(e.Message);
                Debug.WriteLine("Error");
                this.Dispatcher.BeginInvoke(() =>
                {
                    progressBarWait.Visibility = Visibility.Collapsed;
                });
                //这里处理异常，可以在界面上抛出messagebox
            }
        }

        public void ShowApplicationBarState(int current,int total)
        {
            BarButtonFirstPage.IsEnabled = true;
            BarButtonPreviousPage.IsEnabled = true;
            BarButtonNextPage.IsEnabled = true;
            BarButtonLastPage.IsEnabled = true;
            if (current == 1)
            {
                BarButtonFirstPage.IsEnabled = false;
                BarButtonPreviousPage.IsEnabled = false;
            }
            if (current == total)
            {
                BarButtonLastPage.IsEnabled = false;
                BarButtonNextPage.IsEnabled = false;
            }
        }

        protected void DisableApplicationBar()
        {
            BarButtonFirstPage.IsEnabled = false;
            BarButtonPreviousPage.IsEnabled = false;
            BarButtonNextPage.IsEnabled = false;
            BarButtonLastPage.IsEnabled = false;
        }
        #region ApplicationBar
        private void FirstPage_Click(object sender, EventArgs e)
        {
            DisableApplicationBar();
            GoToPage(1);
        }

        private void PreviousPage_Click(object sender, EventArgs e)
        {
            DisableApplicationBar();
            GoToPage(--current_page);
        }

        private void NextPage_Click(object sender, EventArgs e)
        {
            DisableApplicationBar();
            GoToPage(++current_page);
        }

        private void LastPage_Click(object sender, EventArgs e)
        {
            DisableApplicationBar();
            GoToPage(total_page);
        }

        private void Reply_Click(object sender, EventArgs e)
        {
            App.ArticleItemChoose = 0;
            ReplyPopup rp = new ReplyPopup(this);
            PopupContainer pc = new PopupContainer(this);
            pc.Show(rp);

        }

        private void Refresh_Click(object sender, EventArgs e)
        {
            GoToPage(current_page);
        }
        #endregion

        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            base.OnBackKeyPress(e);
           // App.ArticleList.Items.Clear();
        }

        private void ThreadDetailListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            Debug.WriteLine("listbox choose________________________");
            if ((sender as ListBox).SelectedIndex == -1) return;
            if (TapHandled == true)
            {
                App.ArticleItemChoose = (sender as ListBox).SelectedIndex;
                this.NavigationService.Navigate(new Uri("/BYRForum;component/UserInfoPage.xaml", UriKind.Relative));
                TapHandled = false;
                return;
            }
            App.ArticleItemChoose = (sender as ListBox).SelectedIndex;

            if (App.ArticleList.Items[App.ArticleItemChoose].Article_Item.author.Id != App.MyInfo.Id)
            {
                ReplyPopup rp = new ReplyPopup(this);
                PopupContainer pc = new PopupContainer(this);
                pc.Show(rp);
            }
            else
            {
                ManageThreadItem mti = new ManageThreadItem(this);
                PopupContainer pc = new PopupContainer(this);
                pc.Show(mti);
            }

            
            (sender as ListBox).SelectedIndex = -1;
        }

        private void OnImageClick(object sender, RoutedEventArgs e)
        {
            
            TapHandled = true;
        }
    }
}